<template>
    <div class="textDetail">
        <div class="leftBox">

            <el-row>
                <el-col :span="24">
                    <div class="back-home" @click="goBack">
                        <svg width="13" height="10" fill="none" class="mr-1" style="margin-right:5px">
                            <path d="M12.5 5H2m0 0l4 4M2 5l4-4" stroke="#7062F2" stroke-width="1.5"></path>
                        </svg>
                        返回工作台
                    </div>
                </el-col>
            </el-row>

            <div class="filter-group">
                <!-- <h3>🔍 工具分类</h3> -->
                <div>
                    <div class="officeItem" v-for="(item,index) in toolsList" :key="index" :class="toolsItem.appCode==item.appCode?'is-active':''"
                        @click="clickOfficeItem(item)">
                        <!-- <i class="fas fa-briefcase"></i> -->
                        <img :src="item.logoUrl" alt="">
                        <span>{{item.appName}}</span>
                    </div>
                </div>
            </div>

        </div>
        <div class="main-content">

            <div class="title-section">
                <div class="title">{{toolsItem.appName||''}}</div>
                <div class="subtitle">{{toolsItem.appConcent||''}}</div>
            </div>

            <el-row class="input-section">
                <el-col :span="24" v-for="(item,index) in toolsItem.param" :key="index">
                    <div class="label">{{item.label}}：</div>
                    <el-input type="textarea" :rows="4" :placeholder="item.tips" v-model="item.value" class="input-textarea"></el-input>
                </el-col>
            </el-row>

            <el-row class="generate-section">
                <el-col :span="24">
                    <el-button type="primary" class="generate-button" @click="generatePlan" :loading="loading">生成</el-button>
                </el-col>
            </el-row>
            <div class="tipBox">本平台所有产出内容均基于人工智能技术自动生成，相关内容不构成任何形式的官方建议或承诺，用户在使用过程中应根据实际情况自主判断，特此声明。</div>
            <!-- {{progressTxt}} -->
            <!-- <vue-markdown :source="markdown"></vue-markdown> -->
            <!-- <vue-markdown v-loading="progressDone" v-if="progressTxt||progressDone" :source="progressTxt"></vue-markdown> -->
        </div>
        <div class="resultBox">
            <textarea id="MyID"></textarea>
            <!-- {{progressTxt}} -->
            <!-- <EditorTool v-model="progressTxt" style="height:calc(100% - 60px)"></EditorTool> -->
            <!-- <v-md-editor v-loading="progressDone" :editable="false" v-model="progressTxt" :left-toolbar="leftToolbar" :disabled-menus="[]"
                height="calc(100vh - 150px)" /> -->
            <!-- <markdown-editor v-model="progressTxt" ></markdown-editor> -->
        </div>

        <!-- 弹窗 -->
        <!-- <payMemberCard v-if="dialogPayMemberCard" @payEnd='payEnd'></payMemberCard> -->
    </div>
</template>

<script>

import toolBox from "@/api/toolBox";
import tools from '../components/tools'
import VueMarkdown from 'vue-markdown';
import { getToken } from '@/utils/auth'
import { fetchEventSource } from "@microsoft/fetch-event-source";
import SimpleMDE from 'simplemde';
// import '~simplemde/dist/simplemde.min.css';
import { phoneLogin, sendSms, getUserInfo } from "@/api/login";
export default {
    name: 'PlanWriter',
    components: {
        VueMarkdown
    },
    data() {
        return {
            inputText: '',
            loading: false,
            tools: tools.tools,
            toolsItem: {},
            resultText: '',
            dialogPayMemberCard: false,
            sendAnswer: {},
            controller: null,
            progressTxt: '',
            // progressTxt: '# a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n # a\n ',
            // progressTxt: '<div style="font-family: Arial, sans-serif; line-height: 1.6; padding: 20px; background-color: #f9f9f9; border-radius: 10px;"> <h2>梦境解析</h2> <strong>关键元素：</strong> <ul> <li>🐭 <strong>老鼠：</strong> 在荣格理论中，老鼠可能象征着被忽视的小问题或内心的不安。在中国传统文化中，老鼠有时被视为智慧和机敏的象征，但也可能代表小人的骚扰或琐碎的烦恼。</li> <li>💡 <strong>情感基调：</strong> 梦见老鼠通常与焦虑、不安或对某些事情的担忧有关。</li> <li>🔄 <strong>重复模式：</strong> 如果老鼠在梦中反复出现，可能提示您正在经历某种持续的压力或未解决的问题。</li> </ul> <strong>情绪诊断：</strong> 这个梦境可能反映了您近期面临的某种压力或不安感，可能是由于生活中的小问题累积导致的。也可能提示您在某个方面感到无力或受到干扰。 <strong>建议：</strong> <ol> <li>记录下最近几天让您感到焦虑的具体事件，尝试找出其中的共性，以便更好地应对。</li> <li>进行冥想练习，每天花10-15分钟静心，帮助自己放松并减轻焦虑感。</li> <li>与信任的朋友或家人分享您的感受，寻求他们的支持和建议。</li> </ol> <em>注：梦境存在多种解读可能，若此类梦境反复出现，建议通过专业心理测评进一步探索。</em> </div>',
            speed: 0,
            progressDone: false,
            toolsList: [],
            leftToolbar:
                "preview h bold italic strikethrough quote | ul ol table hr | link image code | undo redo clear | save export import", // 左侧工具栏
            rightToolbar: "preview toc sync-scroll fullscreen", // 右侧工具栏
            simplemde: null,
        };
    },
    watch: { // 监听,当路由发生变化的时候执行
        '$route': { // $route可以用引号，也可以不用引号
            handler(to, from) {
                if (this.$route.query.appCode) {
                    this.appCode = this.$route.query.appCode
                    this.queryAppInfoByCodeM()
                }
            },
            deep: true, // 深度观察监听
            immediate: true, // 第一次初始化渲染就可以监听到
        }
    },
    created() {
        this.queryAllAgentM()
    },
    mounted() {
        this.simplemde = new SimpleMDE({
            element: document.getElementById("MyID")

        });
        this.simplemde.codemirror.on("change", () => {

            // this.converterValue = new showdown.Converter().makeHtml(
            //     this.simplemde.value()
            // );
            // console.log(this.simplemde.value());
            // console.log(this.converterValue);
        });

        // this.simplemde.value('# nihao ');

        // console.log(this.simplemde.value());
        // setTimeout(() => {
        //     this.simplemde.togglePreview()
        // }, 1000)
        // setInterval(() => {
        // }, 2000)
        // this.simplemde.value('# aaa');
        // simplemde.co

    },
    methods: {
        clickOfficeItem(item) {
            if (item.appCode != this.toolsItem.appCode) {

                this.$router.replace("/textDetail?appCode=" + item.appCode);
            }
        },
        // 全部智能体
        queryAllAgentM() {
            toolBox.queryAllAgent().then(val => {
                if (val.code == 200) {
                    this.toolsList = val.data
                }
            })
        },
        // 关闭支付弹窗
        payEnd() {
            this.dialogPayMemberCard = false
        },
        // 获取智能体详情
        queryAppInfoByCodeM() {
            toolBox.queryAppInfoByCode({
                appCode: this.appCode
            }).then(val => {
                if (val.code == 200) {
                    this.toolsItem = val.data
                    this.toolsItem.param = JSON.parse(this.toolsItem.param)
                    if (this.simplemde.value()) {
                        this.simplemde.togglePreview(false)
                        this.simplemde.value('')
                        this.progressTxt = ''
                    }
                }
            })
        },
        // 生成方案
        generatePlan() {
            // 生成方案的逻辑
            // console.log('生成方案:', this.inputText);

            if (this.simplemde.value()) {
                this.simplemde.togglePreview(false)
                this.simplemde.value('')
                this.progressTxt = ''
            }
            let inputs = {}
            let that = this
            for (var i in this.toolsItem.param) {
                if (!this.toolsItem.param[i].value) {
                    this.$modal.msgWarning("请输入" + this.toolsItem.param[i].label + "内容");
                    return
                }
                else {
                    inputs[this.toolsItem.param[i].key] = this.toolsItem.param[i].value
                }
            }
            let times = 0
            this.controller = new AbortController() // 终止or结束会话，做了个全局的...

            toolBox.agentCheckSupport(
                {
                    appCode: "DEEP_SEEK_R1_673B",
                }).then(val => {
                    if (val.code == 200) {
                        fetchEventSource(process.env.VUE_APP_BASE_API + '/api/agent/workflows/run', {
                            method: 'POST',
                            headers: {

                                'Content-Type': 'application/json',
                                'Accept': '*/*',
                                'Authorization': 'Bearer ' + getToken(),
                            },
                            body: JSON.stringify(
                                {
                                    inputs: inputs,
                                    appCode: this.appCode
                                }
                            ),
                            openWhenHidden: true,
                            signal: this.controller.signal,
                            onmessage: (msg) => {
                                // console.log('SSE会在通过事件源收到数据时触发')
                                // console.log('接口返回', JSON.parse(msg.data))
                                const msgData = JSON.parse(msg.data)
                                //我这里是判断我请求回来的数据里是否包含'[DONE]'，他是数组里的最后一项，表示加载完成
                                if (!msgData.event.includes('node_finished')) {
                                    // const data = JSON.parse(msg.data)
                                    // const text = msgData.data.text
                                    // const percent = msgData.percent
                                    const message = msgData.data.text
                                    if (msgData.event === 'node_started') {
                                        // 连接成功，开始检测逻辑
                                        this.progressDone = true
                                        // this.progressValue = 0
                                        // this.progressTxt = '数据检查中，该过程可能需要一段时间，请勿关闭窗口'

                                        // this.getTurnCheck()
                                        return false
                                    }
                                    //定时器，控制进度条和文字的展示速度
                                    this.speed += 300
                                    // this.timer = setTimeout(() => {
                                    // console.log(message);
                                    if (message) {
                                        // this.progressDone = false
                                        console.log(message);
                                        // this.progressTxt = this.progressTxt.replace(/<p>|<\/p>/g, '') + message
                                        this.progressTxt = this.progressTxt + message

                                        this.simplemde.value(this.progressTxt);
                                        document.getElementsByClassName('CodeMirror-scroll')[0].scrollTop = document.getElementsByClassName('CodeMirror-sizer')[0].scrollHeight
                                        // this.simplemde.togglePreview()

                                        // setTimeout(() => {
                                        //     this.progressTxt
                                        // },1000)

                                        // this.progressTxt = this.progressTxt + message
                                    }
                                    // this.progressValue = Number(percent)
                                    // if (!this.progressDone) {

                                    //     this.stopSSE()
                                    // }
                                    // }, this.speed)
                                }
                                console.log(msgData.event);
                                if (msgData.event.includes('workflow_finished')) {
                                    this.simplemde.togglePreview()

                                }

                            },
                            onclose: () => {
                                console.log('connection closed')
                                    this.agentSupport().then(val => {
                                        this.$store.dispatch("setFreeTimes", val.msg)
                                    })
                            },
                            onerror: (err) => {
                                console.log(err)
                            },
                            onopen: (response) => {

                                this.agentSupport().then(val => {
                                    this.$store.dispatch("setFreeTimes", val.msg)
                                })
                                return Promise.resolve()
                            },
                        })
                    }
                })
        },
        getTurnCheck() {

        },
        goBack() {
            this.$router.replace({ path: '/' });
        }
    }
};
</script>

<style lang="scss" scoped>
.textDetail {
    // text-align: center;
    width: 100vw;
    min-width: 1000px;
    background-color: #fff;
    display: flex;
    // .centerBox {
    // width: 100%;
    // max-width: 1200px;
    // margin: 0 auto;
    .leftBox {
        width: 260px;
        max-width: 1200px;
        border-right: 1px solid #e0e0e0;
        padding: 20px;

        .back-home {
            display: flex;
            align-items: center;
            color: #7062f2;
            text-decoration: none;
            cursor: pointer;
            margin-bottom: 20px;
        }
        .filter-group {
            h3 {
                margin-bottom: 1rem;
                color: var(--primary);
                font-weight: 600;
                padding-left: 0.5rem;
            }
            .is-active {
                background: rgba(99, 102, 241, 0.15);
                color: var(--primary);
                font-weight: 500;
                border-radius: 0.75rem;
            }
            .officeItem {
                height: 56px;
                line-height: 56px;
                font-size: 14px;
                color: #909399;
                padding: 0 20px;
                list-style: none;
                cursor: pointer;
                position: relative;
                -webkit-transition: border-color 0.3s, background-color 0.3s,
                    color 0.3s;
                transition: border-color 0.3s, background-color 0.3s, color 0.3s;
                -webkit-box-sizing: border-box;
                box-sizing: border-box;
                white-space: nowrap;
                display: flex;
                align-items: center;
                span {
                    margin-left: 10px;
                    font-size: 16px;
                }
                img {
                    width: 20px;
                    height: 20px;
                }
            }
        }
    }
    .main-content {
        width: calc((100% - 260px) / 2);
        max-width: 1200px;
        padding: 20px;
        border-right: 1px solid #e0e0e0;
        .title-section {
            display: flex;
            align-items: center;
            .title {
                font-size: 30px;
                font-weight: bold;
                color: #333;
            }
            .subtitle {
                font-size: 12px;
                color: #666;
                margin-left: 20px;
            }
        }
        .input-section {
            margin-top: 20px;
            .label {
                margin-bottom: 10px;
            }
            .input-textarea {
                width: 100%;
            }
        }
        .generate-section {
            margin: 20px 0;
            text-align: center;
            .generate-button {
                width: 50%;
            }
        }
        .tipBox {
            margin-top: 100px;
            font-size: 12px;
            color: #999;
            padding: 0 50px;
        }
        .examples-section {
            margin-top: 40px;
            .examples-title {
                font-size: 1.5rem;
                color: #666;
                text-align: center;
                margin-bottom: 20px;
            }
            .example-card {
                .example-content {
                    .example-input {
                        font-size: 1rem;
                        color: #333;
                        margin-bottom: 10px;
                    }
                    .example-output {
                        font-size: 0.9rem;
                        color: #999;
                    }
                }
            }
        }
    }
    .resultBox {
        width: calc((100% - 260px) / 2);
        ::v-deep .editor-toolbar {
            border-top: none;
            border-left: none;
            border-right: none;
            border-bottom: 1px solid #bbb;
        }
        ::v-deep .CodeMirror {
            height: calc(100% - 90px) !important;
            border: none !important;
        }
        ::v-deep .editor-statusbar {
            position: absolute !important;
            bottom: 0;
            z-index: 100;
        }
    }
    // }
}
</style>